package sivak.net.proc.dyn.double_lib;

import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA.
 * User: ZefiR
 * Date: 25.01.13
 * Time: 22:31
 * To change this template use File | Settings | File Templates.
 */
public class DoubleLLUtils {
    public static DoubleNode add(DoubleNode tail, int elem) {
        if (tail == null)
            return new DoubleNode(elem, null, null);
        while (tail.next != null) {
            tail = tail.next;
        }
        tail.next = new DoubleNode(elem, tail, null);
        return tail.next;
    }

    public static DoubleNode remove(DoubleNode tail) {
      if (tail == null)
          throw new IllegalArgumentException();
      if (tail.next == null)
          return null;
      while (tail.next.next != null)
          tail = tail.next;
      tail.next = null;
        return  tail;
    }

    public static DoubleNode add(DoubleNode tail, int index, int elem) {
        if (index == 1) {
            tail = new DoubleNode(elem, null, tail);
            tail.next.prev = tail;
            return tail;
        }
        DoubleNode current = tail;
        for (int k = 1; k < index - 1; k++)
            current = current.next;
        current.next = new DoubleNode(elem, current, current.next);
        current.next.next.prev = current.next;
        return tail;
    }

    public static DoubleNode remove(DoubleNode tail, int index) {
        if (tail == null)
            throw new IllegalArgumentException();
        if (index == 1) {
            tail.next.prev = null;
            return tail.next;
        }
        DoubleNode current = tail;
        for (int k = 1; k < index; k++)
            current = current.next;
        current.next.prev = current.prev;
        current.prev.next = current.next;
        return tail;
    }

}
